package com.ccteam.fluidmusic.ui.local.tag

import android.app.Activity
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.IntentSenderRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.viewModels
import com.ccteam.fluidmusic.R
import com.ccteam.fluidmusic.databinding.DialogLocalMusicTagEditBinding
import com.ccteam.fluidmusic.utils.EventObserver
import com.ccteam.fluidmusic.view.bean.LoadMessage
import com.ccteam.taglib.core.MediaTag
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author Xiaoc
 * @since 2021/4/9
 */
@AndroidEntryPoint
class LocalMusicTagEditFragment: BottomSheetDialogFragment()  {

    private var _binding: DialogLocalMusicTagEditBinding? = null
    private val binding get() = _binding!!

    private val localMusicTagViewModel by viewModels<LocalMusicTagViewModel>()

    private val requestShaderIntent = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) {
        if(it.resultCode == Activity.RESULT_OK){
            editMediaTag()
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = DialogLocalMusicTagEditBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        localMusicTagViewModel.mediaTagInfo.observe(viewLifecycleOwner, {
            updateEditTag(it)
        })

        localMusicTagViewModel.editLoadMessage.observe(viewLifecycleOwner,EventObserver{
            binding.btnSaveTag.setLoading(it is LoadMessage.Loading)
            if(it is LoadMessage.Success){
                Snackbar.make(view,getString(R.string.description_edit_tag_success), Snackbar.LENGTH_SHORT).show()
            } else if(it is LoadMessage.Error){
                Snackbar.make(view,getString(R.string.description_edit_tag_fail), Snackbar.LENGTH_SHORT).show()
            }

        })

        binding.btnSaveTag.setOnClickListener {
            localMusicTagViewModel.mediaUri.value?.let { uri ->
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
                    val intent = MediaStore.createWriteRequest(requireContext().contentResolver, listOf(uri))
                    requestShaderIntent.launch(IntentSenderRequest.Builder(intent).build())
                } else {
                    editMediaTag()
                }
            }
        }
    }

    private fun editMediaTag(){
        localMusicTagViewModel.setMediaTag(
            binding.editTitle.editText?.text.toString(),
            binding.editTrack.editText?.text.toString(),
            binding.editYear.editText?.text.toString(),
            binding.editGenre.editText?.text.toString(),
            binding.editArtist.editText?.text.toString(),
            binding.editComposer.editText?.text.toString(),
            binding.editAlbum.editText?.text.toString(),
            binding.editComment.editText?.text.toString(),
            binding.editAlbumArtist.editText?.text.toString(),
            binding.editCopyright.editText?.text.toString()
        )
    }

    private fun updateEditTag(tag: MediaTag) = with(binding){
        editTitle.editText?.setText(tag.title)
        editTrack.editText?.setText(tag.track.toString())
        editYear.editText?.setText(tag.year.toString())
        editAlbum.editText?.setText(tag.album)
        editAlbumArtist.editText?.setText(tag.albumArtist)
        editComposer.editText?.setText(tag.composer)
        editArtist.editText?.setText(tag.artist)
        editComment.editText?.setText(tag.comment)
        editCopyright.editText?.setText(tag.copyright)
        editGenre.editText?.setText(tag.genre)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}